package io.gitee.twoke.generator.engine.impl.util;
import cn.hutool.core.collection.CollectionUtil;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public class TaskUtil {

    public static  <T> void startWithMultiThread(List<T> data, int nThread, Consumer<T> consumer) {
        if (CollectionUtil.isEmpty(data)) return;
        if (nThread <= 0) return;
        if (Objects.isNull(consumer)) return;
        Semaphore semaphore = new Semaphore(nThread);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(nThread, nThread, 0, TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(nThread));

        for (T datum : data) {
            try {
                semaphore.acquire();
                executor.execute(() -> {
                    try {
                        consumer.accept(datum);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        semaphore.release();
                    }
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
//        executor.shutdown();

    }
}
